package com.projectxxxxxxxxxx.utils;

import java.lang.reflect.Method;

import android.util.Log;

public class VMRuntimeHack {
	private static final String TAG = VMRuntimeHack.class.getSimpleName();
	private Object runtime = null;
	private Method trackAllocation = null;
	private Method trackFree = null;

	public VMRuntimeHack() {
		try {
			final Class cl = Class.forName("dalvik.system.VMRuntime");
			final Method method = cl.getMethod("getRuntime", new Class[0]);
			runtime = method.invoke(null, new Object[0]);
			trackAllocation = cl.getMethod("trackExternalAllocation", new Class[] { long.class });
			trackFree = cl.getMethod("trackExternalFree", new Class[] { long.class });
		} catch (Exception e) {
			Log.e(TAG, "VMRuntime hack does not work!", e);
			runtime = null;
			trackAllocation = null;
			trackFree = null;
		}
	}

	public boolean trackAlloc(long size) {
		if (runtime == null) {
			return false;
		}
		try {
			final Object res = trackAllocation.invoke(runtime, Long.valueOf(size));
			return (res instanceof Boolean) ? (Boolean) res : true;
		} catch (Exception e) {
			return false;
		}
	}

	public boolean trackFree(long size) {
		if (runtime == null) {
			return false;
		}
		try {
			final Object res = trackFree.invoke(runtime, Long.valueOf(size));
			return (res instanceof Boolean) ? (Boolean) res : true;
		} catch (Exception e) {
			return false;
		}
	}
}
